import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig } from 'axios';
import type { RequestConfig, RequestHookInterceptors } from './type';

const DEFAULT_LOADING = false;

export default class Request {
    instance: AxiosInstance;
    interceptors?: RequestHookInterceptors;
    showLoading?: Boolean;
    loading?: any;

    constructor(config: RequestConfig) {
        this.instance = axios.create(config); // 实例
        this.interceptors = config.interceptors; // 拦截器
        this.showLoading = config.showLoading ?? DEFAULT_LOADING; // loading

        // 提取实例中的拦截器
        this.instance.interceptors.request.use(
            this.interceptors?.requestInterceptor,
            this.interceptors?.requestInterceptorCatch
        );

        this.instance.interceptors.response.use(
            this.interceptors?.responseInterceptor,
            this.interceptors?.responseInterceptorCatch
        );
        
        // 处理接收到的拦截器
        this.instance.interceptors.request.use(
            (config) => {
                if (this.showLoading) {
                    // 打开loading
                }

                return config;
            },
            (error) => console.error("接收到的拦截器错误")
        )
        this.instance.interceptors.response.use(
            (res) => {
                // 关闭loading
                // ...
                // 提取配置数据
                return res.data;
            },
            (err) => {
                if (err.response.status == 404) {
                    console.log('404错误');
                }
                console.error('实例的失败响应拦截');
                // 关闭loading
            }
        );
    }
}